import React, { useEffect, useState } from "react"
import { Form, Space, Radio, DatePicker, InputNumber, Select, Table, Button, Icon, Input, Popover, Switch, Divider, Tooltip } from '@bytedance/mona-ui';
import type { ColumnProps } from '@bytedance/mona-ui/es/components/table';
import { pritFlotRadio, skuSetingoptions, minskySeletcoption, skutypenameRadio } from './ltalpFunc'
const { Option } = Select;


function SkuKuUi(props) {
    const { itemdata, onChangeItem } = props
    if (!itemdata) return null
    // console.log('itemdata', itemdata)
    const [itemKucunConfig, setItemKucunConfig] = useState(itemdata)
    const { kucuntype, bai, len } = itemKucunConfig
    useEffect(() => {
        if (itemKucunConfig !== itemdata) {
            onChangeItem && onChangeItem(itemKucunConfig)
        }
    }, [itemKucunConfig])
    useEffect(() => {
        if (itemKucunConfig !== itemdata) { 
            setItemKucunConfig(itemdata)
        }
    }, [itemdata])
    return (<>
        {/* <div className="topcontent">123456</div> */}
        <Space>
            <span>活动sku库存</span>
            <Select value={kucuntype} size="small" style={{ width: 140 }} onChange={(e) => {
                // console.log(e)
                setItemKucunConfig({ ...itemKucunConfig, kucuntype: e })
            }}>
                <Option value="1">SKU全部库存</Option>
                <Option value="2">SKU百分比库存</Option>
                <Option value="3">SKU统一库存</Option>
            </Select>
            {kucuntype === '2' &&
                <InputNumber min={1} max={100} value={bai} unit='%' style={{
                    width: 60,
                    minWidth: 60
                }} size="small" onChange={(e) => {
                    setItemKucunConfig({ ...itemKucunConfig, bai: e || 1 })
                }} />
            }
            {kucuntype === '3' &&
                <InputNumber min={1} max={999999} value={len} unit='个' style={{
                    width: 90,
                    minWidth: 60
                }} size="small" onChange={(e) => {
                    setItemKucunConfig({ ...itemKucunConfig, len: e || 1 })
                }} />
            }
        </Space>
    </>)
}
function AddLtalpPritConfig(props) {
    const { configData, indexItem, onDeleteImageItem, onChangeItem, itSkuStatus } = props

    if (!configData) return null
    // console.log(configData)
    const [configDataUse, setConfigDataUse] = useState(JSON.parse(JSON.stringify(configData)))

    let { pritType,
        skuSeting,
        pritFlot,
        flotNum,
        typeName,
        aotoPrtMin,
        showAll } = configDataUse
    // useEffect(() => {
    //     if (configData !== configDataUse) {

    //         setConfigDataUse({ ...configData })
    //     }
    //     return
    // }, [configData])
    useEffect(() => {
        let keyter = true
        configDataUse[itlenKey].forEach((item, index) => {
            if ((item.skymin * 1) >= (item.skymax * 1)) {
                // console.log('item', item)
                // console.log('第', index + 1, '个价格区间不合适')
                keyter = false
                return
            }
            if (((item.skymax * 1) - (item.skymin * 1)) < 0.02) {
                // console.log('item', item)
                // console.log('第', index + 1, '个价格区间不合适相差过小')
                keyter = false
            }
        })
        // if (keyter) {
        //     console.log('价格区间合适')
        // }
        if (configDataUse !== configData) {
            onChangeItem && onChangeItem(configDataUse)
            return
        }
    }, [configDataUse])
    const [linNumPx] = useState((() => {
        const list: any = []
        for (let index = 0; index < 20; index++) {
            list.push({
                label: `${index + 1}个`,
                value: index + 1
            })
        }
        return list
    })())

    const itlenKey = `type${pritType}AllConfig`
    const itlenMinConfKey = `type${pritType}MinConfigStatus`
    const itlenMinKey = `type${pritType}MinConfig`




    interface ColumnPropsType {
        index: number;
        name: string;
    }
    const addLtaLpPrittable: ColumnProps<ColumnPropsType>[] = [{
        title: '序号',
        key: '0',
        align: "center",
        width: 68,
        render: (text: any, record: any, index: number) => {
            return `配置 ${indexItem + 1}`
        }
    }, {
        title: '类型',
        key: '1',
        align: "center",
        width: 69,
        dataIndex: 'typeName'
    }, {
        title: 'sku价格，库存限制购',
        key: '2',
        align: "left",
        width: 310,
        render: (text: any, record: any, index: number) => {
            return (<>
                {record[itlenKey].map((item, index) => {
                    return (<div key={index}>
                        <Space direction="vertical">
                            <Space>
                                <span>{item.skymin} 元</span>
                                <span>&lt;=SKU价格&lt;</span>
                                <span>{item.skymax} 元</span>
                            </Space>
                            <Space>
                                <span>{typeName}:{item.prit}{(record.pritType === '0' || record.pritType === '1') ? '元' : '折'}</span>
                                <span>限领{item.lin}个</span>
                                <span>{item.kucuntype == "0" ? '不限制库存' : item.kucuntype == "1" ? `库存(全部)` : item.kucuntype == "2" ? `库存(${item.bai}%)` : `库存(${item.len}个)`}</span>
                            </Space>
                        </Space>
                        {(index !== record[itlenKey].length - 1) && <Divider style={{
                            margin: '5px 0'
                        }}></Divider>}

                    </div>)
                })}
            </>)
        }
    },
    // {
    //     title: '最低sku',
    //     key: '3',
    //     align: "left",
    //     width: 220,
    //     render: (text: any, record: any, index: number) => {
    //         if (!record[itlenMinConfKey]) return '/'
    //         const item: any = record[itlenMinKey]
    //         return <Space direction="vertical">
    //             <Space>
    //                 <span>{typeName}:{item.prit}{(record.pritType === '0' || record.pritType === '1') ? '元' : '折'}</span>
    //                 <span>限领{item.lin}个</span>
    //                 <span>{item.kucuntype == "0" ? '不限制库存' : item.kucuntype == "1" ? `库存(全部)` : item.kucuntype == "2" ? `库存(${item.bai}%)` : `库存(${item.len}个)`}</span>
    //             </Space>
    //             <Space size={2}>
    //                 同低SKU:{minskySeletcoption.find((items) => {
    //                     return items.value === item.minskust
    //                 })?.label}
    //             </Space>
    //         </Space>
    //     }
    // }, {
    //     title: 'sku设置',
    //     key: '4',
    //     align: "center",
    //     width: 131,
    //     render: (text: any, record: any, index: number) => {
    //         const titlecontent = skuSetingoptions.find((item) => {
    //             return item.value === record.skuSeting

    //         })
    //         return titlecontent ? titlecontent.label : '/'
    //     }
    // },
    {
        title: '适配最低优惠',
        key: '4',
        align: "center",
        width: 131,
        render: (text: any, record: any, index: number) => {
            if (record.aotoPrtMin) return '自动'
            return '不适配'
            // const titlecontent = skuSetingoptions.find((item) => {
            //     return item.value === record.skuSeting

            // })
            // return titlecontent ? titlecontent.label : '/'
        }
    },
    {
        title: '小数位数',
        key: '5',
        align: "center",
        render: (text: any, record: any, index: number) => {
            const getTer = record.pritFlot

            return getTer === '0' ? '保留两位小数' : getTer === '1' ? '保留一位小数' : getTer === '2' ? '保留整数' : `手动输入: ${record.flotNum}`
        }
    }, {
        title: '操作',
        key: '5',
        align: "center",
        render: (text: any, record: any, index: number) => {
            return (<Space>
                <Space>
                    <Button type="link" icon={<Icon type={record.showAll ? "DirectionUpIcon" : "DirectionDownIcon"}></Icon>} onClick={() => {
                        setConfigDataUse({
                            ...configDataUse,
                            showAll: !record.showAll
                        })
                    }}>{record.showAll ? '收起' : '展开'}</Button>
                </Space>
                <Space>
                    {/* <Button type="link" disabled={editLtalpStatus.status} style={{ color: '#F11717' }} icon={<Icon type="DeleteIcon"></Icon>} onClick={() => {
                        onDeleteImageItem && onDeleteImageItem()
                    }}>删除</Button> */}
                    <Button type="link" style={{ color: '#F11717' }} disabled={itSkuStatus.status} icon={<Icon type="DeleteIcon"></Icon>} onClick={() => {
                        // onDeleteImageItem && onDeleteImageItem()
                        onDeleteImageItem && onDeleteImageItem()
                    }}>删除</Button>
                </Space>
            </Space>)
        }
    }]

    return (
        <Space direction="vertical" style={{ width: '100%' }}>
            <Table size="small" columns={addLtaLpPrittable} dataSource={[configDataUse]} style={{ width: '100%' }} pagination={false} rowKey="pritType"></Table>
            {showAll && <Form
                labelCol={{ span: 3 }}
                wrapperCol={{ span: 28 }}
                layout="horizontal"
                name="ltaPritConfig"
                initialValues={configDataUse}
            >
                <Form.Item
                    label="价格,库存,限购"
                >
                    <Space direction="vertical">
                        <Space>
                            <Radio.Group size="small" value={pritType} onChange={(e) => {
                                const val = e.target.value
                                typeName = skutypenameRadio.find((item) => {
                                    return item.value === val
                                })?.name
                                // if(val === '2') {
                                //     aotoPrtMin = false
                                // } else {
                                //     aotoPrtMin = true
                                // }

                                setConfigDataUse({ ...configDataUse, pritType: val, typeName })
                                // setConfigDataUse({ ...configDataUse, pritType: e.target.value })
                            }}>
                                {skutypenameRadio.map((items, indexs) => {
                                    return <Radio value={items.value} key={indexs}>{items.label}</Radio>
                                })}

                            </Radio.Group>
                        </Space>
                        <Space direction="vertical">
                            <Space direction="vertical">
                                {configDataUse[itlenKey].map((item, index) => {
                                    return <Space key={index} align="center">
                                        <div className="text-primary" style={{
                                            width: 37
                                        }}>
                                            第{index + 1}组
                                        </div>
                                        <InputNumber
                                            size="small"
                                            style={{ width: 120 }}
                                            value={item.skymin}
                                            min={(() => {
                                                if (index === 0) return 0
                                                if ((configDataUse[itlenKey][index - 1].skymin * 1) >= 99999999.99) return 99999999.99
                                                return Number(((configDataUse[itlenKey][index - 1].skymin * 1) + 0.01).toFixed(2))
                                            })()}
                                            max={99999999.99}
                                            disabled={index == 0}
                                            // formatter={value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                            // parser={(value = '') => value.replace(/\$\s?|(,*)/g, '')}
                                            onChange={(e) => {
                                                if (configDataUse[itlenKey][index - 1]) {
                                                    configDataUse[itlenKey][index - 1].skymax = e
                                                }
                                                item.skymin = e

                                                setConfigDataUse({ ...configDataUse })
                                            }} />
                                        <span className="text-primary">
                                            &lt;=SKU价格&lt;
                                        </span>
                                        <InputNumber
                                            size="small"
                                            style={{ width: 120 }}
                                            value={item.skymax}
                                            min={(() => {
                                                if (index === 0) return 0
                                                if ((item.skymin * 1) >= 99999999.99) return 99999999.99
                                                return Number(((item.skymin * 1) + 0.01).toFixed(2))
                                            })()}
                                            max={99999999.99}
                                            disabled={index == (configDataUse[itlenKey].length - 1) || configDataUse[itlenKey].length === 1}
                                            // formatter={value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                            // parser={(value = '') => value.replace(/\$\s?|(,*)/g, '')}
                                            onChange={(e) => {
                                                item.skymax = e
                                                if (configDataUse[itlenKey][index + 1]) {
                                                    configDataUse[itlenKey][index + 1].skymin = e
                                                }
                                                setConfigDataUse({ ...configDataUse })
                                            }} />
                                        <span className="text-primary">
                                            {skutypenameRadio.find((item) => {
                                                return item.value === pritType
                                            })?.name}
                                        </span>
                                        <InputNumber
                                            size="small"
                                            unit={pritType === '0' || pritType === '1' ? '元' : '折'}
                                            style={{ width: 60 }}
                                            value={item.prit}
                                            // formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                            // parser={(value = '') => value.replace(/\$\s?|(,*)/g, '')}
                                            onChange={(e) => {
                                                item.prit = e
                                                setConfigDataUse({ ...configDataUse })
                                            }} />
                                        <span className="text-primary">
                                            每人限购
                                        </span>
                                        <Select value={item.lin} size="small" style={{ width: 80 }} onChange={(e) => {
                                            item.lin = e
                                            setConfigDataUse({ ...configDataUse })
                                        }}>
                                            {linNumPx.map((lin, index) => {
                                                return <Option value={lin.value} key={index}>{lin.label}</Option>
                                            })}

                                        </Select>
                                        <Popover placement="top" trigger="click" content={
                                                                                <>
                                                                                <Space>
                                                                                        <span>活动sku库存1</span>
                                                                                        <Select value={item.kucuntype} size="small" style={{ width: 140 }} onChange={(e) => {
                                                                                            // console.log(e)
                                                                                            // setItemKucunConfig({ ...itemKucunConfig, kucuntype: e })
                                                                                            item.kucuntype = e
                                                                                            setConfigDataUse({ ...configDataUse })
                                                                                        }}>
                                                                                            <Option value="1">SKU全部库存</Option>
                                                                                            <Option value="2">SKU百分比库存</Option>
                                                                                            <Option value="3">SKU统一库存</Option>
                                                                                        </Select>
                                                                                        {item.kucuntype === '2' &&
                                                                                            <InputNumber min={1} max={100} value={item.bai} unit='%' style={{
                                                                                                width: 60,
                                                                                                minWidth: 60
                                                                                            }} size="small" onChange={(e) => {
                                                                                                item.bai = e
                                                                                                setConfigDataUse({ ...configDataUse })
                                                                                                // setItemKucunConfig({ ...itemKucunConfig, bai: e || 1 })
                                                                                            }} />
                                                                                        }
                                                                                        {item.kucuntype === '3' &&
                                                                                            <InputNumber min={1} max={999999} value={item.len} unit='个' style={{
                                                                                                width: 90,
                                                                                                minWidth: 60
                                                                                            }} size="small" onChange={(e) => {
                                                                                                // setItemKucunConfig({ ...itemKucunConfig, len: e || 1 })
                                                                                                item.len = e
                                                                                                setConfigDataUse({ ...configDataUse })
                                                                                            }} />
                                                                                        }
                                                                                    </Space>
                                                                                </>
                                                                                
                                        // <SkuKuUi itemdata={item} onChangeItem={(e) => {

                                        //     Object.keys(e).forEach(key => {
                                        //         item[key] = e[key]
                                        //     })
                                        //     setConfigDataUse({ ...configDataUse })
                                        // }}></SkuKuUi>
                                        
                                        }>
                                            <Button size="small" disabled={item.kucuntype == "0"} icon={item.kucuntype !== "0" && <Icon type="EditIcon" />}>
                                                {item.kucuntype == "0" ? '不限制库存' : item.kucuntype == "1" ? `库存(全部)` : item.kucuntype == "2" ? `库存(${item.bai}%)` : `库存(${item.len}个)`}
                                            </Button>
                                        </Popover>
                                        {index === configDataUse[itlenKey].length - 1 ? <Button type="link" icon={<Icon type="AddIcon"></Icon>} onClick={() => {
                                            const addItemCopyData = JSON.parse(JSON.stringify({ ...item }))
                                            addItemCopyData.skymin = addItemCopyData.skymax
                                            // if (type0AllConfig[index - 1]) {
                                            //     // type0AllConfig[index - 1].
                                            //     addItemCopyData.skumin = type0AllConfig[index - 1].skymax
                                            // }
                                            configDataUse[itlenKey].push(addItemCopyData)

                                            // addItemCopyData.skymin = 
                                            setConfigDataUse({ ...configDataUse })
                                        }}></Button> : <Button type="link" style={{
                                            color: 'red'
                                        }} icon={<Icon type="DeleteIcon" onClick={() => {
                                            configDataUse[itlenKey].splice(index, 1)
                                            configDataUse[itlenKey].forEach((itemis, index) => {
                                                if (configDataUse[itlenKey][index - 1]) {
                                                    configDataUse[itlenKey][index - 1].skymax = itemis.skymin
                                                }
                                                if (configDataUse[itlenKey][index + 1]) {
                                                    configDataUse[itlenKey][index + 1].skymin = itemis.skymax
                                                }
                                                if (index === 0) {
                                                    itemis.skymin = 0
                                                }
                                            })
                                            setConfigDataUse({ ...configDataUse })
                                        }}></Icon>}></Button>}
                                    </Space>
                                })}
                            </Space>
                        </Space>
                    </Space>
                </Form.Item>
                {false && <>

                    <Form.Item
                        label="最低价sku"
                    >
                        <Space >
                            <Switch checkedChildren={'单独'} unCheckedChildren={'统一'} size="small" checked={configDataUse[itlenMinConfKey]} onChange={(e) => {
                                configDataUse[itlenMinConfKey] = e
                                setConfigDataUse({ ...configDataUse })
                            }} />
                            {configDataUse[itlenMinConfKey] && <Space>

                                <span className="text-primary">
                                    {skutypenameRadio.find((item) => {
                                        return item.value === pritType
                                    })?.name}
                                </span>
                                <InputNumber
                                    size="small"
                                    unit={pritType === '0' || pritType === '1' ? '元' : '折'}
                                    style={{ width: 60 }}
                                    value={configDataUse[itlenMinKey].prit}
                                    // formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                    // parser={(value = '') => value.replace(/\$\s?|(,*)/g, '')}
                                    onChange={(e) => {
                                        configDataUse[itlenMinKey].prit = e
                                        setConfigDataUse({ ...configDataUse })
                                    }} />
                                <span className="text-primary">
                                    每人限购
                                </span>
                                <Select value={configDataUse[itlenMinKey].lin} size="small" style={{ width: 80 }} onChange={(e) => {
                                    configDataUse[itlenMinKey].lin = e
                                    setConfigDataUse({ ...configDataUse })
                                }}>
                                    {linNumPx.map((lin, index) => {
                                        return <Option value={lin.value} key={index}>{lin.label}</Option>
                                    })}

                                </Select>
                                <Popover placement="top" trigger="click" content={<SkuKuUi itemdata={configDataUse[itlenMinKey]} onChangeItem={(e) => {

                                    Object.keys(e).forEach(key => {
                                        configDataUse[itlenMinKey][key] = e[key]
                                    })
                                    setConfigDataUse({ ...configDataUse })
                                }}></SkuKuUi>}>
                                    <Button size="small" disabled={configDataUse[itlenMinKey].kucuntype == "0"} icon={configDataUse[itlenMinKey].kucuntype !== "0" && <Icon type="EditIcon" />}>
                                        {configDataUse[itlenMinKey].kucuntype == "0" ? '不限制库存' : configDataUse[itlenMinKey].kucuntype == "1" ? `库存(全部)` : configDataUse[itlenMinKey].kucuntype == "2" ? `库存(${configDataUse[itlenMinKey].bai}%)` : `库存(${configDataUse[itlenMinKey].len}个)`}
                                    </Button>
                                </Popover>
                                <span className="text-primary">
                                    相同最低价SKU选择方式
                                </span>
                                <Select value={configDataUse[itlenMinKey].minskust} size="small" style={{ width: 180 }} onChange={(e) => {
                                    // console.log(e)
                                    configDataUse[itlenMinKey].minskust = e
                                    setConfigDataUse({ ...configDataUse })
                                }}>
                                    {minskySeletcoption.map((items, indexs) => {
                                        return <Option value={items.value} key={indexs}>{items.label}</Option>
                                    })}

                                </Select>
                            </Space>
                            }
                        </Space>

                    </Form.Item>
                    <Form.Item
                        label="SKU 设置"
                    >
                        <Select value={skuSeting} size="small" style={{ width: 180 }} onChange={(e) => {
                            setConfigDataUse({ ...configDataUse, skuSeting: e })
                        }}>
                            {skuSetingoptions.map((items, indexs) => {
                                return <Option value={items.value} key={indexs}>{items.label}</Option>
                            })}

                        </Select>
                    </Form.Item></>}
                <Form.Item label="适配最低优惠">
                    <Space>
                        <Switch checked={aotoPrtMin} size="small" onChange={(e) => {
                            setConfigDataUse({ ...configDataUse, aotoPrtMin: e })
                        }}></Switch>
                        <Tooltip title="开启后将自动适配活动的最低可设置优惠，确保活动创建成功">
                            <Icon type=""></Icon>
                        </Tooltip>
                    </Space>
                </Form.Item>
                {pritType !== "2" && <>
                    <Form.Item
                        label="价格小数位数"
                    >
                        <Space>

                            <Radio.Group value={pritFlot} size="small" onChange={(e) => {
                                setConfigDataUse({ ...configDataUse, pritFlot: e.target.value })
                            }}>
                                {pritFlotRadio.map((items, indexs) => {
                                    return <Radio value={items.value} key={indexs}>{items.label}</Radio>
                                })}

                            </Radio.Group>
                            <Input value={flotNum} placeholder="00-99" size="small" style={{ width: 100 }} disabled={pritFlot !== "3"} onChange={(e) => {
                                let val = e.target.value
                                var allowedChars = '0123456789';

                                // 检查每个字符是否在允许的字符内
                                for (var i = 0; i < val.length; i++) {
                                    if (allowedChars.indexOf(val[i]) === -1) {
                                        // 不在允许的字符内，移除该字符
                                        val = val.replace(val[i], '');
                                    }
                                }

                                // 如果输入的是0开头的数字，则允许
                                if (val.length > 1) {
                                    // 保留第二位数字
                                    val = val.substring(0, 2);
                                }

                                // 只能输入00-99的数字
                                // let value = e.target.value
                                // if (value.length > 2) {
                                //     value = value.slice(0, 2)
                                // }
                                // if (value.length == 1) {
                                //     value = "0" + value
                                // }
                                // if (value.length == 0) {
                                // }
                                // setFlotNum(value)
                                setConfigDataUse({ ...configDataUse, flotNum: val })
                                // setConfigDataUse({ ...configDataUse, flotNum: e.target.value })
                            }}>
                            </Input>
                        </Space>

                    </Form.Item>
                </>}
            </Form>}
        </Space>
    )
}

export default AddLtalpPritConfig